<?php
/**
 * Created by PhpStorm.
 * User: zhang
 * Date: 2018/6/29
 * Time: 8:22
 */


namespace app\shopping\model;

use app\common\model\Base;

class OrderManager extends Base{

    const DEFAULT_STATE=1;
    const DB_NAME="sopp_indent";

    private $orderInfo;

    const ORDER_OBLIGATION = 1; //待付款
    const ORDER_PAID = 2;
    const ORDER_RECEIVING = 3;
    const ORDER_DEALSUCCESS = 4;
    const ORDER_DEALCANCEL = 5;
    const ORDER_DEALCLOSE = 6;
    const ORDER_PENDING = 7;
    const ORDER_PROCESSED = 8;
    const ORDER_REFUNDED = 9;

    const UNPAID = 0;

    public function __construct(){
        parent::__construct();

        $args=func_get_args();
        $argsNum=func_num_args();

        if(method_exists($this,$f='__construct'.$argsNum)) {
            //若存在xx方法，使用call_user_func_array(arr1,arr2)函数调用他,该函数的参数为两个数组，前面的数组为调用谁($this)的什么($f)方法，后一个数组为参数
            call_user_func_array(array($this, $f), $args);
        }
    }

    public function __construct1($uid){
        //echo "222";
        //$this->orderInfo = $this->getOrderById($uid);
    }

    public function __construct2($uid,$mode){
        //$this->orderInfo = $this->getOrderById($uid,$mode);
    }

    public function createOrder($uid,$userAddress){
        $newOrder = array(
            "indent_id"=>$this->CreateOrderId(),        //订单号id
            "uid"=>$uid,                                 //用户uid
            "datetime"=>dateFormat(),
            "indent_state"=>self::DEFAULT_STATE,
            $userAddress
        );

        var_dump($newOrder);
        //$this->mysql->insertSQL(self::DB_NAME,$newOrder);
    }

    /*
     * 更新订单状态
     * 1：待付款，2：待发货或已付款，3：待收货，4：交易成功，5：交易取消，6：交易关闭,7：待处理,8:已处理,9：已退款
     * $status PAID=1 UNPAID=0;
     */
    public function updateOrder($id, $status=SELF::UNPAID){
        $order = $this->getOrderById($id);
        $orderOldState = $order["indent_state"];
        if($orderOldState==SELF::ORDER_OBLIGATION){
            if($status == SELF::UNPAID){
                return false;
            }else if($status == SELF::ORDER_PAID){
                $result = $this->updateOrderByCustom(array("indent_id"=>$id),array("indent_state"=>($orderOldState+1)));
            }else if($status == SELF::ORDER_DEALCANCEL){
                $result = $this->updateOrderByCustom(array("indent_id"=>$id),array("indent_state"=>SELF::ORDER_DEALCANCEL));
            }else{
                return false;
            }
        }else if($orderOldState == SELF::ORDER_DEALSUCCESS){
            return false;
        }else{
            $result = $this->updateOrderByCustom(array("indent_id"=>$id),array("indent_state"=>($orderOldState+1)));
        }
/*
       if($status == SELF::UNPAID || $orderOldState==SELF::ORDER_DEALSUCCESS
           || $orderOldState==SELF::ORDER_DEALCANCEL||$orderOldState==SELF::ORDER_DEALCLOSE) {
            return false;
       }else if($status <= $orderOldState){
           return false;
       }else{
           $result = $this->updateOrderByCustom(array("indent_id" => $id), array("indent_state" => $status));
       }
*/
        return $result;
    }

    public function removeOrder(){

    }

    /*
     *  通过ID获取订单
     * @para $page//参数
    */
    public function getAllOrders($page=0,$indent_state=0){
        if($indent_state==0)
            return $this->getOrdersByCustom(null,$page);
        return $this->getOrdersByCustom(array("indent_state"=>$indent_state),$page);
    }

    /*
     *  通过ID获取订单
     *
    */
    public function getOrderById($id){
        $result = $this->getOrdersByCustom(array("indent_id"=>$id));

        return $result==null?false:$result[0];
    }

    public function getOrderByUid($Uid){
        $result = $this->getOrdersByCustom(array("Uid"=>$Uid,"indent_state"=>2));

        return $result==null?false:$result;
    }

    public function getStateCount($state){
        if($state == 0)
            return $this->getCount();
        return $this->getCount(array("indent_state"=>$state));
    }

    private function getCount($customKey=[]){
        if(count($customKey) == 0){
            $orderSql = "select COUNT(*) AS count from " .SELF::DB_NAME;
        }else{
            $condition = null;
            foreach ($customKey as $key=>$value){
                //echo "Key: $key; Value: $value<br />\n";
                if($condition==null){
                    $condition = $condition." $key='$value'";
                }else{
                    $condition = $condition." and $key='$value'";
                }

            }
            $orderSql = "select COUNT(*) AS count from " .SELF::DB_NAME. " where " .$condition;
        }

        return $this->mysql->selectSQLRow($orderSql)["count"];
    }

    public function getOrdersByCustom($customKey=[],$page=0){
        if(count($customKey) == 0){
            $orderSql = "select * from " .SELF::DB_NAME. " LIMIT $page,10";
        }else{
            $condition = null;
            foreach ($customKey as $key=>$value){
                //echo "Key: $key; Value: $value<br />\n";
                if($condition==null){
                    $condition = $condition." $key='$value'";
                }else{
                    $condition = $condition." and $key='$value'";
                }

            }

            $page = (intval($page))*10;
            $orderSql = "select * from " .SELF::DB_NAME. " where " .$condition. " LIMIT $page,10";
        }
        $data = $this->mysql->selectSQLAll($orderSql);
        $indent = new Indent();
        for($i=0;$i<10;$i++){
            $result = $indent->getIndentComm($data[$i]["indent_id"]);

            if($result)
                $data[$i]["comm"] = $result;
        }

        return $data;
    }

    private function updateOrderByCustom($saveCondition,$saveSequence=[]){
        $conditionSql = null;
        $SequencceSql = null;
        foreach ($saveCondition as $key=>$value){
            //echo "Key: $key; Value: $value<br />\n";
            if($conditionSql==null){
                $conditionSql = $conditionSql."$key='$value'";
            }else{
                $conditionSql = $conditionSql." and $key='$value'";
            }
        }

        foreach ($saveSequence as $key=>$value){
            //echo "Key: $key; Value: $value<br />\n";
            if($SequencceSql==null){
                $SequencceSql = $SequencceSql."$key='$value'";
            }else{
                $SequencceSql = $SequencceSql.",$key='$value'";
            }
        }

        $orderSql = "update " .SELF::DB_NAME. " set ".$SequencceSql." where " .$conditionSql;

        return $this->mysql->updateSQL($orderSql);
    }
    /*
     *  生成一个新的订单ID
     */
    private function CreateOrderId(){
        $orderSql = "SELECT indent_id FROM sopp_indent ORDER BY id DESC  LIMIT 1";
        $maxOrderNum = $this->mysql->selectSQL($orderSql)["indent_id"];

        if($maxOrderNum){
            $maxOrderNum = preg_replace('/\D/s', '', $maxOrderNum); //去除字母
            $maxOrderNum = 'SD' . $this->addLargeNumber($maxOrderNum, '1');
            return $maxOrderNum;
        }else{
            return $indent_id = "SD00000000000001";
        }

        return false;
    }
    /*
     *  添加1
     */
    private function addLargeNumber($a, $b) {
        $lenA = strlen($a);
        $lenB = strlen($b);
        $j = 0;
        $re = '';
        for ($inxA = $lenA - 1, $inxB = $lenB - 1; ($inxA >= 0 || $inxB >= 0); --$inxA, --$inxB) {
            $itemA = ($inxA >= 0) ? (int) $a[$inxA] : 0;
            $itemB = ($inxB >= 0) ? (int) $b[$inxB] : 0;
            $sum = $itemA + $itemB + $j;
            if ($sum > 9) {
                $j = 1;
                $sum = $sum - 10;
            } else {
                $j = 0;
            }
            $re = (string) $sum . $re;
        }
        if ($j > 0) {
            $re = (string) $j . $re;
        }
        return $re;
    }

}